# 服务： 你们发送的信息，我可以原样发回
import socket
from threading import Thread

class Server(object):
    def __init__(self, addr="192.168.13.21", port=9999):
        self.addr = addr
        self.port = port
        self.user_list = []

    def recv_send(self, username, client_sc, client_addr):
        while True:
            try:
                msg = client_sc.recv(1024).decode()  # 先收
                print(f"来自 {username}的消息：{msg}")
                if msg.startswith('@') and msg.find(' ') != -1:
                    name,mg = msg.split(' ',1)

                # client_sc.send("收到了".encode())  # 原样回给你
                for i in self.user_list:
                    if i[0] != username:
                        i[1].send((f'{username}的消息：{msg}').encode())
            except ConnectionResetError:

                print(f"{username,client_addr} 断开了连接！")
                self.user_list.remove([username, client_sc])
                for j in self.user_list:
                    j[1].send((f'{username}退出群聊.').encode())
                break
            except Exception as e:
                print(f"{client_addr} 连接错误！")
                break

    def start(self):
        self.s = socket.socket()
        self.s.bind((self.addr, self.port))
        self.s.listen(10)
        while True:
            client_sc, client_addr = self.s.accept()  # 返回的是 (socket object, address info)
            # print(client_sc,client_addr)
            client_sc.send((f'欢迎来自{client_addr}的朋友，请输入你的姓名：').encode())
            username = client_sc.recv(1024).decode()
            print(f"{username}:{client_addr}加入群聊。")
            temp_list = [username,client_sc]
            self.user_list.append(temp_list)
            for i in self.user_list:
                i[1].send((f'欢迎{username}加入群聊.').encode())
            t = Thread(target=self.recv_send, args=(username,client_sc,client_addr))
            t.start()

    def __del__(self):
        self.s.close()


if __name__ == '__main__':
    s1 = Server()
    s1.start()
